// 谷歌登录回调
import { useEffect, useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { request } from '@/api/request';
import { jwtDecode } from 'jwt-decode';

interface GoogleLoginCallbackResult {
  loading: boolean;
  error: string | null;
  data: any | null;
  processCallbackCode: (code: string) => Promise<void>;
  processTokenFromUrl: () => void;
}

export const useGoogleLoginCallback = (): GoogleLoginCallbackResult => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [data, setData] = useState<any | null>(null);
  const navigate = useNavigate();
  const location = useLocation();

  // Process the callback code (original method)
  const processCallbackCode = async (code: string) => {
    setLoading(true);
    setError(null);
    try {
      const response = await request.post('/auth/google-login-callback', { code });
      
      if (response.data.success && response.data.data) {
        setData(response.data.data);
        
        // Check if token is provided in the response
        if (response.data.data.token) {
          // Store the token and user data
          const token = response.data.data.token;
          
          try {
            const decoded = jwtDecode(token);
            // Check if it's the user's first login
            if (decoded && (decoded as any).isFirstLogin === true) {
              localStorage.setItem('just_registered', 'true');
              // Navigate with success parameter for new users
              navigate('/?registration=success');
            } else {
              // Regular navigation for returning users
              navigate('/');
            }
          } catch (e) {
            console.error('Failed to decode token:', e);
            // Default navigation if token decoding fails
            navigate('/');
          }

          // Store user data
          const userData = {
            visitor_uuid: response.data.data.uuid || '',
            user_avatar: response.data.data.avatar || '',
            visitor_token: token,
            login_type: 'google',
            user_email: response.data.data.email || '',
            user_displayName: response.data.data.displayName || '',
            vip_live: (response.data.data.membership_tier || null),
            tokens_balance: response.data.data.tokens_balance || 0
          };
          
          localStorage.setItem('userData', JSON.stringify(userData));
          
          // Trigger event to notify other components
          window.dispatchEvent(new CustomEvent('userLoginStatusChanged'));
          
        }
      } else {
        setError(response.data.message || 'Failed to login with Google');
      }
    } catch (err: any) {
      console.error('Google login callback error:', err);
      setError(err.response?.data?.message || 'Failed to process Google login');
    } finally {
      setLoading(false);
    }
  };

  // New method to process token directly from URL
  const processTokenFromUrl = () => {
    setLoading(true);
    setError(null);
    
    try {
      // Get URL parameters
      const params = new URLSearchParams(window.location.hash.substring(2) || window.location.search);
      const token = params.get('token');
      const isFirstLogin = params.get('isFirstLogin');
      const tokens_balance = params.get('tokens_balance');
      
      if (!token) {
        // console.log('No token found in URL');
        setLoading(false);
        return;
      }
      
      // Decode token
      const decoded = jwtDecode<any>(token);
      // console.log('Decoded token:', decoded);
      
      // Check if this is first login from URL parameter or token
      if (isFirstLogin === 'true' || decoded.isFirstLogin === true) {
        // console.log('Setting just_registered flag to true');
        localStorage.setItem('just_registered', 'true');
        // Navigate to home with registration success parameter
        navigate('/?registration=success');
      } else {
        // Regular navigation for returning users
        navigate('/');
      }
      
      // Store user data
      const userData = {
        visitor_uuid: decoded.uuid || '',
        user_avatar: decoded.avatar || '',
        visitor_token: token,
        login_type: 'google',
        user_email: decoded.email || '',
        user_displayName: decoded.displayName || '',
        vip_live: decoded.membership_tier || null,
        tokens_balance: tokens_balance ? parseInt(tokens_balance) : 0
      };
      
      // console.log('Storing user data:', userData);
      localStorage.setItem('userData', JSON.stringify(userData));
      
      // Trigger event to notify other components
      window.dispatchEvent(new CustomEvent('userLoginStatusChanged'));
      
      // Clean URL
      const cleanUrl = window.location.pathname;
      window.history.replaceState({}, document.title, cleanUrl);
      
    } catch (err) {
      console.error('Failed to process token from URL:', err);
      setError('Failed to process login information');
    } finally {
      setLoading(false);
    }
  };

  // Auto-process either code or token from URL
  useEffect(() => {
    // Check for token in hash or search params
    const hashParams = new URLSearchParams(window.location.hash.substring(2));
    const searchParams = new URLSearchParams(location.search);
    
    const token = hashParams.get('token') || searchParams.get('token');
    const code = hashParams.get('code') || searchParams.get('code');
    
    if (token) {
      // console.log('Found token in URL, processing...');
      processTokenFromUrl();
    } else if (code) {
      // console.log('Found code in URL, processing...');
      processCallbackCode(code);
    }
  }, [location]);

  return {
    loading,
    error,
    data,
    processCallbackCode,
    processTokenFromUrl
  };
};

export default useGoogleLoginCallback; 